
import re
import wx
import wx.stc as stc

import IconImages

import ConfigUtil
import syntax.lua

#----------------------------------------------------------------------

demoText = """\
## Python comment
-- Comment
-- [[ Comment ]]
Number = 12345
String = 'abcde'
String = "abcde"
String = [[ ABCDE ]]
## Python comment

debug = debug
function F(V)
    for a, b in ipairs(t):
        string.len(a)
    end
end

"""

#----------------------------------------------------------------------


if wx.Platform == '__WXMSW__':
    faces = { 'times': 'Times New Roman',
              'mono' : 'Courier New',
              'helv' : 'Arial',
              'other': 'Comic Sans MS',
              'size' : 10,
              'size2': 8,
             }
else:
    faces = { 'times': 'Times',
              'mono' : 'Courier',
              'helv' : 'Helvetica',
              'other': 'new century schoolbook',
              'size' : 12,
              'size2': 10,
             }


#----------------------------------------------------------------------

# Load colors

colorpath = 'colors/default.colors'
configdict = None

def LoadColors(ctrl):
    global configdict
    if configdict == None:
        configdict = ConfigUtil.LoadConfigDictFromFile(colorpath)

    lua = re.compile(r'^[0-9A-Z]+$')
    style = re.compile(r'^[0-9A-Z_]+$')
    for k, v in configdict.items():
        if lua.match(k):
            k = eval('stc.STC_LUA_'+k)
            ctrl.StyleSetSpec(k, v)
        elif style.match(k):
            k = eval('stc.'+k)
            ctrl.StyleSetSpec(k, v)
        else:
            pass

    if configdict.has_key('caretforeground'):
        ctrl.SetCaretForeground(configdict['caretforeground'])
    if configdict.has_key('selbackground'):
        ctrl.SetSelBackground(1, configdict['selbackground'])
    if configdict.has_key('selforeground'):
        ctrl.SetSelForeground(1, configdict['selforeground'])


def SetColorPath(path):
    global colorpath
    colorpath = path

def SetConfigDict(d):
    global configdict
    configdict = d

#----------------------------------------------------------------------

class LuaSTC(stc.StyledTextCtrl):

    fold_symbols = 2
    
    def __init__(self, parent, ID,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0):
        stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style)

        self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
        self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)

        self.SetLexer(stc.STC_LEX_LUA)
        self.SetKeyWords(0, " ".join(syntax.lua.word))
        self.SetKeyWords(1, " ".join(syntax.lua.word2))
        self.SetKeyWords(2, " ".join(syntax.lua.word3))
        self.SetKeyWords(3, " ".join(syntax.lua.word4))

        self.SetViewWhiteSpace(False)
        #self.SetBufferedDraw(False)
        #self.SetViewEOL(True)
        #self.SetEOLMode(stc.STC_EOL_CRLF)
        #self.SetUseAntiAliasing(True)
        
        #self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
        #self.SetEdgeColumn(78)


        self.SetIndent(4)               # Proscribed indent size for wx
        self.SetIndentationGuides(True) # Show indent guides
        self.SetBackSpaceUnIndents(True)# Backspace unindents rather than delete 1 space
        self.SetTabIndents(True)        # Tab key indents
        self.SetTabWidth(4)             # Proscribed tab size for wx
        self.SetUseTabs(False)          # Use spaces rather than tabs, or


        self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)

        # Make some styles,  The lexer defines what each style is used for, we
        # just have to define what each style looks like.  This set is adapted from
        # Scintilla sample property files.

        self.StyleClearAll()  # Reset all to be like the default

        LoadColors(self)


        # register some images for use in the AutoComplete box.
        self.RegisterImage(1, IconImages.getSmilesBitmap())
        self.RegisterImage(2, 
            wx.ArtProvider.GetBitmap(wx.ART_NEW, size=(16,16)))
        self.RegisterImage(3, 
            wx.ArtProvider.GetBitmap(wx.ART_COPY, size=(16,16)))




    def OnUpdateUI(self, evt):
        # check for matching braces
        braceAtCaret = -1
        braceOpposite = -1
        charBefore = None
        caretPos = self.GetCurrentPos()

        if caretPos > 0:
            charBefore = self.GetCharAt(caretPos - 1)
            styleBefore = self.GetStyleAt(caretPos - 1)

        # check before
        if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_LUA_OPERATOR:
            braceAtCaret = caretPos - 1

        # check after
        if braceAtCaret < 0:
            charAfter = self.GetCharAt(caretPos)
            styleAfter = self.GetStyleAt(caretPos)

            if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_LUA_OPERATOR:
                braceAtCaret = caretPos

        if braceAtCaret >= 0:
            braceOpposite = self.BraceMatch(braceAtCaret)

        if braceAtCaret != -1  and braceOpposite == -1:
            self.BraceBadLight(braceAtCaret)
        else:
            self.BraceHighlight(braceAtCaret, braceOpposite)
            #pt = self.PointFromPosition(braceOpposite)
            #self.Refresh(True, wxRect(pt.x, pt.y, 5,5))
            #print pt
            #self.Refresh(False)





#----------------------------------------------------------------------

_USE_PANEL = 1

def runTest(frame, nb, log):
    if not _USE_PANEL:
        ed = p = LuaSTC(nb, -1)
    else:
        p = wx.Panel(nb, -1, style = wx.NO_FULL_REPAINT_ON_RESIZE)
        ed = LuaSTC(p, -1)
        s = wx.BoxSizer(wx.HORIZONTAL)
        s.Add(ed, 1, wx.EXPAND)
        p.SetSizer(s)
        p.SetAutoLayout(True)


    ed.SetText(demoText + open('../src/toydebugger.lua').read())
    ed.EmptyUndoBuffer()
    ed.Colourise(0, -1)

    # line numbers in the margin
    ed.SetMarginType(1, stc.STC_MARGIN_NUMBER)
    ed.SetMarginWidth(1, 25)

    return p



#----------------------------------------------------------------------


if __name__ == '__main__':
    import sys,os
    import wxrun
    wxrun.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])





#----------------------------------------------------------------------
#----------------------------------------------------------------------

# vim: expandtab:shiftwidth=4:
